package com.fm.mqtt;

import com.fm.websocket.ClientMessage;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by Administrator on 2018/8/7 0007.
 */
@Controller
public class PushCallback implements MqttCallback {

    public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连
        System.out.println("连接断开，可以做重连");
    }

    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
//        topic = "/"+topic;
        TopicUtils topicUtils = new TopicUtils();

        //sys 0:sys 1:产品Key 2:设备名 3：thing 4：event or service 5：property or 事件名 6：post
        String topicParams [] = topic.split("/");
        String productKey = "";
        String deviceName = "";
        String eventName = "";
        String revice = new String(message.getPayload());
        ClientMessage client = ClientMessage.getInstance();
//        client.runStompClient(client, "/mqtt", topic+"-T-"+revice, null);
        try {
            if (topicParams[1].equals("sys")){
                productKey = topicParams[2];
                deviceName = topicParams[3];
                if(topicParams[5].equals("event")&&topicParams.length>7) {
                    if (topicParams[6].equals("property")){//属性上报
                        topicUtils.doPostProperty(productKey,deviceName,revice);
                    }else {
                        eventName = topicParams[6];
                        topicUtils.doPostEvent(productKey,deviceName,eventName,revice);
                    }
                }else if (topicParams[6].equals("login")) {
                    topicUtils.doLogin(productKey,deviceName,revice);
                }else if (topicParams[6].equals("logout")) {
                    topicUtils.doLogout(productKey,deviceName,revice);
                }
            }else {
                productKey = topicParams[1];
                deviceName = topicParams[2];
            }
        }catch (Exception e) {
            e.printStackTrace();
            System.out.print("topic不正确！");
        }
        // subscribe后得到的消息会执行到这里面
        System.out.println("接收消息主题 : " + topic);
        System.out.println("接收消息Qos : " + message.getQos());
        System.out.println("接收消息内容 : " + revice);

    }
}
